package core.java;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Scanner;

/**
 * @Author SSK
 * @Date Created in 1:28 2019/8/24
 * @Description TODO
 * @Version 1.0
 */
public class IoClient {
        private SocketChannel socket;
        final private int PORT;
        final private String IP;
        private boolean run;
        public IoClient(int port) {
            this(port,"127.0.0.1");
        }
        public IoClient(int port, String IP) {
            this.PORT = port;
            this.IP = IP;
            this.run = false;
        }
        public void start() throws IOException {
            Scanner scanner = new Scanner(System.in);
            socket = SocketChannel.open();
            this.run = true;
            socket.connect(new InetSocketAddress(IP,PORT));
            socket.configureBlocking(false);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.clear();
            while (run) {
                byteBuffer.put((scanner.next()).getBytes("utf-8"));
                byteBuffer.flip();
                socket.write(byteBuffer);
                byteBuffer.clear();
                byteBuffer.put("endl".getBytes("utf-8"));
                byteBuffer.flip();
                socket.write(byteBuffer);
                byteBuffer.clear();
               while (socket.read(byteBuffer)!=-1) {
                   if (byteBuffer.position()==0) {
                       //System.out.println(byteBuffer);
                       continue;
                   }
                   String s =new String(Arrays.copyOfRange(byteBuffer.array(),0,byteBuffer.position()),"utf-8");
                   byteBuffer.clear();
                   if (s.indexOf("endl")!=-1) {
                       System.out.println(s.substring(0,s.indexOf("endl")));
                       break;
                   }
                   System.out.println(s);

               }

            }
            socket.close();
        }
        public void stop(){
            this.run = false;
        }
    public static void main ( String[] args) throws IOException {
        IoClient ioClient = new IoClient(8000);
        ioClient.start();

    }
}
